package com.pactera.demo.base.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.demo.base.dto.ResourceDto;
import com.pactera.demo.base.entity.Resource;
import com.pactera.demo.base.service.IResourceService;
import com.pactera.demo.common.dto.ResponseResult;
import com.pactera.demo.common.enums.StatusCodeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源权限表 前端控制器
 * </p>
 *
 * @author mybatis.plus
 * @since 2020-02-27
 */
@RestController
@RequestMapping("/base")
public class ResourceController {

    private IResourceService resourceService;

    @PostMapping("/resource")
    public ResponseResult create(@RequestBody @Valid ResourceDto resourceDto, BindingResult result){
        if(result.hasErrors()){
            List<String> errors = result.getAllErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.toList());
            return ResponseResult.fail(StatusCodeEnum.ILLEGAL_PARAM, errors);
        }

        Resource resource = new Resource();
        BeanUtils.copyProperties(resourceDto, resource);
        this.resourceService.save(resource);
        return ResponseResult.success();
    }

    @GetMapping("/resource/{pageSize}/{index}")
    public ResponseResult list(@PathVariable("pageSize")int pageSize,@PathVariable("index") int index){
        IPage<Resource> page = this.resourceService.page(new Page(index,pageSize));
        return ResponseResult.success(page);
    }

    public ResourceController(IResourceService resourceService) {
        this.resourceService = resourceService;
    }
}

